package com.glorysoft.xztpda.ui.trackin

import androidx.databinding.ObservableArrayList
import com.glorysoft.sunnypda.entity.ui.CallObserveBean
import com.glorysoft.xztpda.entity.ui.ToastMessageBean
import com.glorysoft.xztpda.BR
import com.glorysoft.xztpda.R
import com.glorysoft.xztpda.base.BaseViewModel
import com.glorysoft.xztpda.bindingadapter.AddCarrierDataAdapter
import com.glorysoft.xztpda.entity.BOMITEMS
import com.glorysoft.xztpda.entity.CheckMatEntity
import com.glorysoft.xztpda.entity.LotInfoEntity
import com.glorysoft.xztpda.entity.LotList
import com.glorysoft.xztpda.model.LotRepository
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.util.ArrayList

/**
 * FileName: TrackInBaseViewModel
 * Author: XJH
 * Date: 2022/4/12 16:19
 * Description:
 * History:
 */
class TrackInBaseViewModel : BaseViewModel() {

    private val repository: LotRepository = LotRepository()
    var lotInfoEntity: LotInfoEntity? = null
    var scanPos = -1

    val OnScan = object : OnScanListener {
        override fun onItemScanClick(item: LotInfoEntity.Material) {
            scanPos = materialItems.indexOf(item)
            defUI.callObserve.value = CallObserveBean(200, 1000 + scanPos)
        }

    }

    var materialItems = ObservableArrayList<LotInfoEntity.Material>()
    var materialBinding =
            ItemBinding.of<LotInfoEntity.Material>(BR.materielItem, R.layout.item_material_info).bindExtra(BR.onScanClick, OnScan)

    val mStepList: List<String> = arrayListOf("A0300", "B0400", "C0400", "D0300", "E0200", "F0200")

    var mAddCarrierAdapter = AddCarrierDataAdapter(null)

    fun getLotInfo(lot: String, eqp: String) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "LOTINFOBYID")
        map.addProperty("LOTID", lot)
        map.addProperty("EQUIPMENTID", eqp)
        launchOnlyResult({
            lotInfoEntity = repository.getLotInfo(map)
            defUI.callObserve.value = CallObserveBean(0, 0)
        })

    }

    fun trackIn(type: String) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", type)
        map.addProperty("ISCHECKSTEPAUTHORITY", false)
        val lotList: MutableList<LotList> = ArrayList<LotList>()
        lotList.add(LotList(lotInfoEntity?.lot?.lotid))
        map.add("LOTLIST", JsonParser().parse(Gson().toJson(lotList)).asJsonArray) //传批次集合
        if (lotInfoEntity?.trackinwizard != "DefaultTrackIn") {
            map.addProperty("EQUIPMENTID", lotInfoEntity?.eqpid)
        }
        map.addProperty("Step", lotInfoEntity?.lot?.stepname)
        map.add("DURABLEIDLIST", JsonParser().parse(Gson().toJson(lotInfoEntity?.durablelist)).asJsonArray)
        map.add("MLOTLIST", JsonParser().parse(Gson().toJson(materialItems)).asJsonArray)
        if (type == "XztSubCapaTrackIn") {
            map.add("SUBEQUIPMENTIDLIST", JsonParser().parse(Gson().toJson(mAddCarrierAdapter.data)).asJsonArray)
        }
        launchOnlyResult({
            repository.trackIn(map)
            defUI.toastEvent.value = ToastMessageBean("进站成功", true)
            defUI.startActivity.call()
        })

    }

    fun initMaterialList() {
        if (lotInfoEntity?.workorderbomlinelist?.size!! > 0) {
            lotInfoEntity?.workorderbomlinelist?.forEach {
                if (it.stepname == lotInfoEntity?.lot?.stepname) {
                    materialItems.add(it)
                }
            }
        } else {
            lotInfoEntity?.lotassemblylist?.forEach {
                it.reserveD01 = it.unitqty
                if (it.stepname == lotInfoEntity?.lot?.stepname) {
                    materialItems.add(it)
                }
            }
        }
    }

    fun checkEqp(s: String, toString: String) {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "CAPACHECK")
        map.addProperty("LOTID", toString)
        map.addProperty("EQUIPMENTID", s)
        launchWithError({
            repository.checkEqp(map)
            defUI.callObserve.value = CallObserveBean(1, 0)
        }, {
            defUI.callObserve.value = CallObserveBean(2, 0)
        })

    }

    fun checkMaterial(code: String) {
        val map = JsonObject()
        val split = code.split(";")
        if (split.isEmpty() || split.size < 2) {
            defUI.toastEvent.value = ToastMessageBean("扫描物料条码有误", false)
            return
        }

        var data: ArrayList<BOMITEMS> = arrayListOf()
        var mat = BOMITEMS()
        mat.MODID = lotInfoEntity!!.lot.udf.modid
        mat.SCODE = split[0]
        mat.MATERIALNAME = materialItems[scanPos].materialname
        data.add(mat)
        map.add("XXZTBOMITEMS", JsonParser().parse(Gson().toJson(data)).asJsonArray)
        launchOnlyResult({
            val checkMaterial = repository.checkMaterial(map)
            //1.校验通过 是关键物料 正常保存
            //2.校验通过 不是关键物料 正常保存，
            //3.校验不通过 是关键物料 不保存
            //4.校验不通过  不是关键物料 提示 确定后能正常保存
            //G_李志荣:
            //ERRORMSG   提示字段； 这个为空就是校验通过；
            //G_李志荣:
            //ERRORMSG   不为空就是校验不通过要提示 ；
            if (checkMaterial.XXZTBOMITEMS[0].ERRORMSG.isEmpty()) {
                if (scanPos >= 0) {
                    materialItems[scanPos].mlotid = split[1]
                    materialItems[scanPos].reserveD03 = split[0]
                }
            } else {
                if (checkMaterial.XXZTBOMITEMS[0].RESERVED02 != "Y") {
                    defUI.callObserve.value = CallObserveBean(201, code)
                } else {
                    defUI.toastEvent.value = ToastMessageBean(checkMaterial.XXZTBOMITEMS[0].ERRORMSG, false)
                }
            }

        })
    }

    fun checkMaterialList(code: String) {
        val map = JsonObject()
        var data: ArrayList<BOMITEMS> = arrayListOf()
        for (materialItem in materialItems) {
            var mat = BOMITEMS()
            mat.MODID = lotInfoEntity!!.lot.udf.modid
            mat.SCODE = materialItem.reserveD03
            mat.MATERIALNAME = materialItem.materialname
            data.add(mat)
        }
        map.add("XXZTBOMITEMS", JsonParser().parse(Gson().toJson(data)).asJsonArray)
        launchOnlyResult({
            val checkMaterial = repository.checkMaterial(map)
            checkMaterial.XXZTBOMITEMS.forEach {
                if (it.ERRORMSG.isNotEmpty() && it.RESERVED02 == "Y") {
                    defUI.toastEvent.value = ToastMessageBean(it.ERRORMSG, false)
                    return@launchOnlyResult
                }
            }

            trackIn(code)
        })
    }

    fun setMaterial(code: String) {
        val split = code.split(";")
        materialItems[scanPos].mlotid = split[1]
        materialItems[scanPos].reserveD03 = split[0]
    }


    interface OnScanListener {
        fun onItemScanClick(item: LotInfoEntity.Material)
    }
}